package com.atguigu.yuntai.statistics.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yuntai.common.util.NameValueData;
import com.atguigu.yuntai.statistics.bean.QUnified;
import com.atguigu.yuntai.statistics.entity.AdsTradeStatsByCate;
import com.atguigu.yuntai.statistics.mapper.TradeStatsCateMapper;
import com.atguigu.yuntai.statistics.service.TradeStatsCateService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 各品类商品交易实现类
 */
@Service
public class TradeStatsCateServiceImpl extends ServiceImpl<TradeStatsCateMapper, AdsTradeStatsByCate> implements TradeStatsCateService {


    @Override
    public List<JSONObject> getCateTradeStats(QUnified qUnified) {
        List<JSONObject> childrenList = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("recent_days", qUnified.getRecentDays());
        queryWrapper.eq("dt", qUnified.getDt());
        List<AdsTradeStatsByCate> category1List = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(category1List)) {
            for (AdsTradeStatsByCate adsTradeStatsByCate : category1List) {
                JSONObject children1 = new JSONObject();
                JSONArray children2Array = new JSONArray();
                children1.put("name", adsTradeStatsByCate.getCategory1Name());
                queryWrapper.eq("category1_id", adsTradeStatsByCate.getCategory1Id());
                List<AdsTradeStatsByCate> category2List = this.baseMapper.selectList(queryWrapper);
                for (AdsTradeStatsByCate categroy2 : category2List) {
                    JSONObject children2 = new JSONObject();
                    children2.put("name", categroy2.getCategory2Name());
                    children2.put("value", categroy2.getOrderCountTotal());
                    queryWrapper.eq("category2_id", adsTradeStatsByCate.getCategory2Id());
                    List<NameValueData> category3List = this.baseMapper.selectList(queryWrapper);
                    children2.put("children", category3List);
                    children2Array.add(children2);
                }
                children1.put("children", children2Array);
                childrenList.add(children1);
            }
        }
        return childrenList;
    }

}
